package top.go2do.websiteNavigation.business.website.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.go2do.common.annotation.UserInfoFill;
import top.go2do.common.controller.TomatoController;
import top.go2do.common.module.UserInfoBO;
import top.go2do.common.module.pageQuery.PageResult;
import top.go2do.websiteNavigation.business.website.module.*;
import top.go2do.websiteNavigation.business.website.service.WebsiteService;
import top.go2do.websiteNavigation.exception.WebsiteNavigationErrorCode;
import top.go2do.websiteNavigation.exception.WebsiteNavigationException;
import top.go2do.websiteNavigation.utils.ImageUtils;

import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/6/18 13:01
 */
@Slf4j
@RequestMapping("/website")
@RestController
public class WebsiteController implements TomatoController<WebsitePO, WebsiteCreateForm, WebsiteModifyForm, Long, WebsiteQueryCondition, WebsiteQueryAllCondition, WebsiteListVO> {

    @Autowired
    private WebsiteService goodsService;

    @Override
    public WebsitePO create(WebsiteCreateForm createForm, UserInfoBO userInfo) {
        log.info("website create appId:{}, url:{}", userInfo.getAppId(), createForm.getUrl());
        createForm.setUserId(userInfo.getUserId());
        return goodsService.create(createForm);
    }

    @Override
    public void modifyById(Long id, WebsiteModifyForm modifyForm, UserInfoBO userInfo) {
        modifyForm.setWebsiteId(id);
        modifyForm.setUserId(userInfo.getUserId());
        goodsService.modifyById(modifyForm);
    }

    @Override
    public void removeById(Long id, UserInfoBO userInfo) {
        goodsService.removeById(id);
    }

    @Override
    public WebsitePO getById(Long id) {
        return goodsService.getById(id);
    }

    @Override
    public List<WebsiteListVO> listAll(WebsiteQueryAllCondition condition) {
//        List<WebsitePO> poList = goodsService.listAll(condition);
//        List<WebsiteListVO> volist = goodsService.po2vo(poList);
//        return volist;
        return null;
    }

    @Override
    public PageResult<WebsiteListVO> pageQuery(WebsiteQueryCondition goodsQueryCondition) {
//        PageResult<WebsitePO> pageResult = goodsService.pageQuery(goodsQueryCondition);
//        List<WebsiteListVO> volist = goodsService.po2vo(pageResult.getList());
//        PageResult<WebsiteListVO> finalResult = new PageResult<>();
//        BeanUtils.copyProperties(pageResult, finalResult);
//        finalResult.setList(volist);
//        return finalResult;
        return null;
    }

    @Override
    public PageResult<WebsiteListVO> myPageQuery(@UserInfoFill UserInfoBO userInfo, WebsiteQueryCondition websiteQueryCondition) {
        websiteQueryCondition.setUserId(userInfo.getUserId());
        PageResult<WebsitePO> pageResult = goodsService.pageQuery(websiteQueryCondition);
        List<WebsiteListVO> volist = goodsService.po2vo(pageResult.getList());
        PageResult<WebsiteListVO> finalResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, finalResult);
        finalResult.setList(volist);
        return finalResult;
    }

    @PatchMapping("/setTags")
    public void setTags(@Valid @RequestBody WebsiteTagsForm goodsTagsForm, @UserInfoFill UserInfoBO userInfo) {
        goodsTagsForm.setUserId(userInfo.getUserId());
        goodsService.setTags(goodsTagsForm);
    }

    @PostMapping("/urlToIcon")
    public Map<String, String> getUrlIcon(@Valid @RequestBody WebsiteUrlForm websiteUrlForm) throws Exception{
        String url = websiteUrlForm.getUrl();
        log.info("get icon from {}", url);
        Map<String, String> result = new HashMap();
        try {
            URL site = new URL(url);
            Document document = Jsoup.parse(site, 30000);
            Elements linkIcon = null;
            try {
                linkIcon = document.head().getElementsByAttributeValue("rel", "shortcut icon");
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    linkIcon = document.head().getElementsByAttributeValue("rel", "icon");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }

            if (linkIcon == null || linkIcon.isEmpty()) {
                try {
                    linkIcon = document.head().getElementsByAttributeValue("rel", "icon");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }

            String icon;
            if (linkIcon == null || linkIcon.isEmpty()) {
                icon = getUrlPrefix(site) + "favicon.ico";
            } else {
                icon = linkIcon.attr("href");
            }

            if (!icon.contains("http://") && !icon.contains("https://")) {
                icon = getUrlPrefix(site) + icon;
            }
            result.put("url", icon);
            String base64 = "";
            try {
                base64 = ImageUtils.imgUrl2Base64Code(icon);
            } catch (Exception e) {
                e.printStackTrace();
                result.put("base64error", e.getMessage());
            }
            result.put("base64", base64);
        } catch (Exception e) {
            log.warn("get icon error:", e);
            throw new WebsiteNavigationException(WebsiteNavigationErrorCode.WEBSITE_ICON_PARSE_ERROR);
        }
        return result;
    }

    public String getUrlPrefix(URL site) {
        String port = site.getPort() == -1 ? "" : ":" + site.getPort();
        return site.getProtocol() + "://" + site.getHost() + port + "/";
    }
}
